package com.jt.util;

import java.sql.*;

/**
 * jdbc连接数据库的工具类
 */
public class JDBCUtil {

    static{
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     */
    public static Connection getConnection() throws Exception {
        String url = "jdbc:mysql://localhost:3306/cgb2108?characterEncoding=utf8&serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "root";
        Connection conn = DriverManager.getConnection(url,username,password);

        return conn;
    }

    /**
     * 关闭资源
     */
    public static void close(Connection conn, ResultSet rs, Statement stat){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(stat!=null){
            try {
                stat.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


    public static void main(String[] args) throws Exception{
        Connection conn = JDBCUtil.getConnection();
        System.out.println(conn);
    }
}
